package breadbox.pastry.messages;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Serialize objects to and deserialize objects from byte arrays. Copied from
 * breadbox.client.operations.Operation
 * @author Daniel
 *
 */
public class MessageSerializer {
	public static byte[] serialize(Object o) throws IOException {
		ByteArrayOutputStream byte_out = new ByteArrayOutputStream();
		ObjectOutputStream object_out = new ObjectOutputStream(byte_out);
		object_out.writeObject(o);
		object_out.flush();
		object_out.close();
		byte_out.flush();
		byte[] b = byte_out.toByteArray();
		return b;
	}
	
	public static Object deserialize(byte[] b) throws IOException, ClassNotFoundException {
		ByteArrayInputStream byte_in = new ByteArrayInputStream(b);
		ObjectInputStream object_in = new ObjectInputStream(byte_in);
		Object o = object_in.readObject();
		object_in.close();
		byte_in.close();
		return o;
	}
}
